#!/bin/bash

for var in "$@"
do
    if [[ "$var" =~ ^"--"(set|s)"="(.+)""$ ]] ; then
        set="["${BASH_REMATCH[2]}"]"
    else
        echo "unknown argument $var"
        echo "Usage: bash getData.sh --set=\"<full name>\""
        exit 1
    fi
done

if [[ -z $set ]] ; then
    echo "Error: set not set"
    exit 1
fi

setUrl=${set//"["/"%5B"}
setUrl=${setUrl//"]"/"%5D"}
setUrl=${setUrl//"\""/"%22"}
setUrl=${setUrl//" "/"%20"}

function getLastPage {
    wget "http://gatherer.wizards.com/Pages/Search/Default.aspx?page=0&sort=cn+&set=$setUrl" >/dev/null 2>&1 || { echo >&2 "Could not retrieve http://gatherer.wizards.com/Pages/Search/Default.aspx?page=0&sort=cn+&set=$setUrl"; exit 1;}
    
    while read line ; do
    
        if [[ "$line" =~ "<a href=\"/Pages/Search/Default.aspx?page="([0-9]+)"&amp;sort=cn+&amp;set=$setUrl\">&gt;&gt;</a>" ]] ; then
            echo ${BASH_REMATCH[1]}
            break;
        fi
    
    done < "Default.aspx?page=0&sort=cn+&set=$set"
    
    rm "Default.aspx?page=0&sort=cn+&set=$set"
}

function parseForNumbers {
    if [[ -z "$1" ]] ; then
        return
    fi

    while read line ; do
        if [[ $line =~ "<div id=\"ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_ctl00_listRepeater_ctl"[0-9]{2}"_cardSetCurrent\" class=\"rightCol\">" ]]; then
            read line2;
            
            test=$(echo "$line2" | grep -Po '(?<=multiverseid=)[0-9]+')

            echo $test
        elif [[ $line =~ "<div id=\"ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_ctl00_listRepeater_ctl"[0-9]{2}"_cardSets\" class=\"rightCol\">" ]]; then

            read line2;
            
            test=$(echo "$line2" | grep -Po '(?<=multiverseid=)[0-9]+')

            echo $test;
        
        fi
    done < "$1"
}

echo "Getting last page." > /dev/tty
lastPage="`getLastPage`"
echo "Last page set to $lastPage." > /dev/tty

numbers=""

for (( page=0 ; page <= $lastPage ; page++ )) ; do

echo "Parsing page $page." > /dev/tty

wget "http://gatherer.wizards.com/Pages/Search/Default.aspx?page=$page&sort=cn+&set=$setUrl" >/dev/null 2>&1 || { echo >&2 "Could not retrieve http://gatherer.wizards.com/Pages/Search/Default.aspx?page=$page&sort=cn+&set=$setUrl"; exit 1;}

numbers="$numbers `parseForNumbers "Default.aspx?page=$page&sort=cn+&set=$set"`"

rm "Default.aspx?page=$page&sort=cn+&set=$set"

done

echo "Got all numbers." > /dev/tty

echo $numbers
